package com.rykj.qxj.aop;


import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.alibaba.fastjson.JSON;
import com.rykj.qxj.annotation.EnableSystemLog;
import com.rykj.qxj.server.model.entity.SystemLog;
import com.rykj.qxj.server.services.ISystemLogService;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Aspect
@Component
public class SystemLogAspect {
	
	@Autowired
	private ISystemLogService systemLogService;
	
	//定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(com.rykj.qxj.annotation.EnableSystemLog)")
    public void logPoinCut() {
    }
    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        log.info("日志切面开始===================");
        //保存日志
        SystemLog sysLog = new SystemLog();
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //获取操作
        EnableSystemLog annotation = method.getAnnotation(EnableSystemLog.class);
        if (annotation != null) {
            String value = annotation.value();
            sysLog.setOperation(value);//保存获取的操作
            String fullPath = annotation.fullPath();
            sysLog.setPath(fullPath);
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethodName(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
        String params = JSON.toJSONString(args);
        sysLog.setParams(params);
        sysLog.setCreateTime(new Date());
        //获取RequestAttributes  
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();  
        //从获取RequestAttributes中获取HttpServletRequest的信息  
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);  
        log.info("==> 请求者的IP："+request.getRemoteAddr());
        sysLog.setIp(request.getRemoteAddr());
        sysLog.setUsername(request.getHeader("User-Name"));
        log.info("==> 请求者用户名："+request.getHeader("User-Name"));
        systemLogService.saveSystemLog(sysLog);
    }

}

